<template>
  <!-- 编辑页 -->
  <el-form
    label-width="120px"
    :rules="rules"
    :model="spuInfo"
    ref="formRef"
    v-loading="saveLoading"
  >
    <!-- 输入框 -->
    <el-form-item label="SPU名称" prop="spuName">
      <el-input
        style="width: 240px"
        placeholder="SPU名称"
        v-model="spuInfo.spuName"
      ></el-input>
    </el-form-item>
    <!-- 下拉列表 -->
    <el-form-item label="品牌" prop="tmId">
      <el-select class="m-2" placeholder="请选择" v-model="spuInfo.tmId">
        <el-option
          :label="item.tmName"
          :value="item.id!"
          v-for="item in brandList"
          :key="item.id"
        />
      </el-select>
    </el-form-item>
    <!-- 自定义输入框 -->
    <el-form-item label="SPU描述" prop="description">
      <el-input
        :rows="2"
        type="textarea"
        placeholder="SPU描述"
        v-model="spuInfo.description"
      />
    </el-form-item>
    <!-- 上传图片 -->
    <el-form-item label="SPU图片" prop="spuImageList">
      <el-upload
        v-model:file-list="spuInfo.spuImageList as any"
        :action="`${BASE_URL}/admin/product/fileUpload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        multiple
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="item.imgUrl"
          v-for="item in spuInfo.spuImageList"
          :key="item.id"
        />
      </el-dialog>
    </el-form-item>
    <!-- 下拉列表加按钮 -->
    <el-form-item label="销售属性" prop="spuSaleAttrList">
      <el-select
        class="m-2"
        :placeholder="saleAttrListLength()"
        v-model="saleList"
      >
        <el-option
          :label="item.name"
          :value="item.id + ':' + item.name"
          v-for="item in saleAttrList"
          :key="item.id"
        />
      </el-select>
      <el-button type="primary" :disabled="!saleList" @click="addSaleAttr"
        >添加销售属性</el-button
      >
    </el-form-item>
    <!-- 表格 -->
    <el-form-item>
      <el-table border :data="spuInfo.spuSaleAttrList">
        <el-table-column label="序号" type="index" width="120" align="center" />
        <el-table-column label="属性名" prop="saleAttrName" />
        <el-table-column label="属性值名称列表">
          <template #default="{ row, $index }">
            <el-tag
              v-for="item in row.spuSaleAttrValueList"
              :key="item.id"
              style="margin: 5px"
              closable
              >{{ item.saleAttrValueName }}</el-tag
            >
            <el-input
              v-if="row.isInput"
              v-model="InputSaleAttr"
              ref="inputRef"
              @blur="addSaleAttrValue(row)"
            ></el-input>
            <el-button
              v-else
              :icon="Plus"
              size="small"
              @click="toInput(row)"
            ></el-button>
          </template>
        </el-table-column>
        <!-- 增删改查小图标 -->
        <el-table-column label="操作" width="160">
          <template v-slot="{ row, $index }">
            <el-button
              type="danger"
              :icon="Delete"
              size="small"
              @click="spuInfo.spuSaleAttrList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <!-- 保存取消按钮 -->
    <el-form-item>
      <el-button type="primary" @click="confimList"> 保存 </el-button>
      <el-button @click="emit('showSpuState', SpuState.SPU_LIST)">
        取消
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
  import { defineComponent } from "vue";
  import type {
    BaseSaleAttrListModel,
    SpuSaleAttrModel,
    SpuValueModel,
  } from "@/api/product/model/spuModel";
  import { useCategoryStore } from "@/stores/category";
  import {
    addOrUpdateSpuInfoApi,
    getBaseSaleAttrListApi,
    getSpuImageListApi,
    getSpuSaleAttrListApi,
  } from "@/api/product/spu";
  import { getAllTrademarkListApi } from "@/api/product/trademark";
  import type { trandemarkListModel } from "@/api/product/model/trademarkModel";
  import {
    ElMessage,
    type FormInstance,
    type FormRules,
    type InputInstance,
    type UploadProps,
  } from "element-plus";
  import { cloneDeep } from "lodash";
  export default defineComponent({
    name: "SpuForm",
  });
</script>
<script lang="ts" setup>
  import { SpuState } from "../spu";
  import { Plus, Delete } from "@element-plus/icons-vue";
  import { storeToRefs } from "pinia";
  import { ref, onMounted, computed, nextTick } from "vue";

  const emit = defineEmits<{
    (e: "showSpuState", value: SpuState): void;
  }>();

  /* 初始化 start */
  const BASE_URL = import.meta.env.VITE_BASE_URL;
  const prop = defineProps<{
    spu: SpuValueModel;
  }>();
  const spuInfo = ref<SpuValueModel>(prop.spu);

  // const { category3Id } = storeToRefs(useCategoryStore());
  //所有品牌
  const brandList = ref<trandemarkListModel>([]);
  const baseSaleAttrList = ref<BaseSaleAttrListModel>([]);
  // const spuImageList = ref<SpuImageListModel>([]);
  // const spuSaleAttrList = ref<SpuSaleAttrListModel>([]);
  onMounted(async () => {
    //所有基础销售属性
    baseSaleAttrList.value = await getBaseSaleAttrListApi();
  });
  onMounted(async () => {
    //所有品牌属性
    brandList.value = await getAllTrademarkListApi();
  });
  onMounted(async () => {
    //所有图片列表
    if (!spuInfo.value.id) return;
    spuInfo.value.spuImageList = await getSpuImageListApi(spuInfo.value.id);
    spuInfo.value.spuImageList.map((item) => {
      (item.name = item.imgName), (item.url = item.imgUrl);
    });
  });
  onMounted(async () => {
    //销售属性
    if (!spuInfo.value.id) return;
    spuInfo.value.spuSaleAttrList = await getSpuSaleAttrListApi(
      spuInfo.value.id
    );
  });

  //处理销售属性
  const saleAttrList = computed(() => {
    return baseSaleAttrList.value.filter((item) => {
      return !spuInfo.value.spuSaleAttrList.some(
        (i) => i.saleAttrName === item.name
      );
    });
  });

  //收集选择的销售属性
  const saleList = ref("");

  //点击添加销售属性
  const addSaleAttr = () => {
    const [id, name] = saleList.value.split(":");
    spuInfo.value.spuSaleAttrList.push({
      baseSaleAttrId: +id,
      saleAttrName: name,
      spuSaleAttrValueList: [],
    });
    saleList.value = "";
  };

  // '剩余' + saleAttrList.length + '个未选择'
  const saleAttrListLength = () => {
    return saleAttrList.value.length > 0
      ? "剩余" + saleAttrList.value.length + "个未选择"
      : "没有选择啦";
  };
  const inputRef = ref<InputInstance>();
  const toInput = (rou: SpuSaleAttrModel) => {
    rou.isInput = true;
    nextTick(() => {
      inputRef.value?.focus();
    });
  };
  //收集输入的销售属性值
  const InputSaleAttr = ref("");
  //失去焦点或回车按钮添加销售属性值
  const addSaleAttrValue = (row: SpuSaleAttrModel) => {
    if (InputSaleAttr.value) {
      const notRepeat = row.spuSaleAttrValueList.every(
        (item) => item.saleAttrValueName !== InputSaleAttr.value
      );
      if (notRepeat) {
        row.spuSaleAttrValueList.push({
          saleAttrValueName: InputSaleAttr.value,
          baseSaleAttrId: row.baseSaleAttrId,
        });
      }
    }
    row.isInput = false;
    InputSaleAttr.value = "";
  };

  /*  初始化 end */

  /* 上传图片 start */

  const dialogImageUrl = ref("");
  const dialogVisible = ref(false);

  const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
    // console.log(uploadFile, uploadFiles);
    spuInfo.value.spuImageList = uploadFiles as any;
  };

  const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
    spuInfo.value.spuImageList = uploadFile as any;
  };
  const handleSuccess: UploadProps["onSuccess"] = (
    Response,
    UploadFile,
    UploadFiles
  ) => {
    spuInfo.value.spuImageList = UploadFiles as any;
    formRef.value?.clearValidate(["spuImageList"]);
  };
  /* 上传图片 end */

  /* 解决图片的加载问题 end */

  /* 表单验证 start */
  const formRef = ref<FormInstance>();
  const rules: FormRules = {
    spuName: [{ required: true, message: "必须要填SPU名称" }],
    tmId: [{ required: true, message: "必须要选择品牌" }],
    description: [{ required: true, message: "必须要填SPU描述" }],
    spuImageList: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (spuInfo.value.spuImageList.length > 0) {
            callback();
          } else {
            callback("至少上传一张图片");
          }
        },
      },
    ],
    spuSaleAttrList: [
      {
        required: true,
        message: "至少添加一个有属性值的销售属性",
        type: "array",
      },
    ],
  };

  /* 表单验证 end */
  //提交数据发送请求
  const saveLoading = ref(false);
  const confimList = async () => {
    await formRef.value?.validate();

    const cloneSpuInfo = cloneDeep(spuInfo.value);

    cloneSpuInfo.spuImageList = cloneSpuInfo.spuImageList.map((item) => ({
      imgName: item.name!,
      imgUrl: item.response ? item.response.data : item.imgUrl,
    }));

    cloneSpuInfo.spuSaleAttrList = cloneSpuInfo.spuSaleAttrList.filter(
      (item) => {
        if (item.spuSaleAttrValueList.length > 0) {
          delete item.isInput;
          return true;
        }

        return false;
      }
    );
    // 如果一个spu的销售属性都没有了, 不发请求并提示
    if (cloneSpuInfo.spuSaleAttrList.length === 0) {
      ElMessage.warning("必须SPU销售属性!");
      return;
    }
    saveLoading.value = true;
    try {
      await addOrUpdateSpuInfoApi(cloneSpuInfo);
      ElMessage.success("保存信息成功！");
      emit("showSpuState", SpuState.SPU_LIST);
    } catch (error) {
    } finally {
      saveLoading.value = false;
    }
  };
</script>

<style lang="scss" scoped></style>
